/**
 * 全局异常拦截器
 *   使用： 在 main.js 中注册  app.useGlobalFilters(new HttpFilter())
 */

import { Request, Response } from 'express'; // 引入类型
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();

    const status = exception.getStatus();

    // 接口异常返回信息
    response.status(status).json({
      data: exception,
      time: new Date(),
      success: false,
      path: request.url,
      status,
    });
  }
}
